//
//  VerificationVC.m
//  DataStatistics
//
//  Created by Kang on 16/3/10.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "VerificationVC.h"
#import <SMS_SDK/SMSSDK.h>
#import "UtilToolsClass.h"
#import "NetRequestClass.h"
#import "NSString+Extension.h"
@interface VerificationVC () <UITextFieldDelegate, UIAlertViewDelegate> {
    UIToolbar* VVCtoolbar;
    BOOL isClick;
    CGRect frameDefault;
}

@property (strong, nonatomic) IBOutlet UILabel* timeLabel;
//计时
@property (nonatomic, strong) NSTimer* timer2;
@end

// 计时初始值
static int timerCount = 0;
@implementation VerificationVC

- (void)viewDidLoad{
    [super viewDidLoad];
    [self updateUI];
    self.title = NSLocalizedString(@"输入验证码", nil);
    [self.verificationBtn setTitle:NSLocalizedString(@"下一步", nil) forState:UIControlStateNormal];
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backIetm;
    self.navigationItem.hidesBackButton = YES;
}

-(void)backItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    _VerificationText.delegate = self;
    [_VerificationText addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_timer2 invalidate];
}

- (void)updateUI{
    self.textContent.text = NSLocalizedString(@"VERFICATION-PHONE", nil);
    _lblGetSMSPhoneNumber.text = [NSString stringWithFormat:@"+%@ %@",_VVC_areaNam,_VVC_phoneNumber];
    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(VVCkeyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = YES;
    [self.view addGestureRecognizer:tapGestureRecognizer];

    [_againGetSMSBtn setTitle:NSLocalizedString(@"重发", nil) forState:UIControlStateNormal];
    [_againGetSMSBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _VerificationText.clearButtonMode = UITextFieldViewModeUnlessEditing;
    _VerificationText.placeholder = NSLocalizedString(@"请输入验证码", nil);
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.text = @"";

    if (_timer2) {
        [_timer2 invalidate];
    }
    timerCount = 0;
    self.timeLabel.textColor = [UIColor lightGrayColor];

    [self loadingUpdateForTimeLable];
}


/**
 *  启动时间倒计时label
 */
-(void) loadingUpdateForTimeLable{
     NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1
   _timer2 = timer2;
   self.againGetSMSBtn.hidden = YES;
}



/** 更新计时时间*/
- (void)updateTime
{
    timerCount++;
    if (timerCount >= 60) { //60
        self.timeLabel.hidden = YES;
        self.againGetSMSBtn.hidden = NO;
        [_timer2 invalidate];
        return;
    }
    // 翻译说，单数复数问题。1 没有s 大于1有s
    if(timerCount == 1){
         self.timeLabel.text = [NSString stringWithFormat:@"%@ %i %@", NSLocalizedString(@"接收验证码大约需要", nil), 60 - timerCount, NSLocalizedString(@"秒", nil)]; //60
    }else{
         self.timeLabel.text = [NSString stringWithFormat:@"%@ %i %@s", NSLocalizedString(@"接收验证码大约需要", nil), 60 - timerCount, NSLocalizedString(@"秒", nil)]; //60
    }
}

// 输入框内容监控
- (void)textLengthMethod:(UITextField*)textField
{
    // 限制长度
    if (textField == self.VerificationText) {
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
}


- (void)resignRespondersForText
{
    if (isClick) {
        isClick = NO;
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
            POPBasicAnimation *basicAnim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
            basicAnim.toValue = [NSValue valueWithCGRect:CGRectMake(self.view.frame.origin.x, 64, self.view.frame.size.width, self.view.frame.size.height)];
            [self.view pop_addAnimation:basicAnim forKey:@"viewBasicAnim"];
            
            [_VerificationText resignFirstResponder];
    }
    else {
           [self.view endEditing:YES];
     }
   }
}

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (!isClick) {
        isClick = YES;
    }
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
        CGRect newFrome = self.view.frame;
        newFrome.origin.y = 40;
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        }];
    }
}

// 手势方法键盘隐藏
- (void)VVCkeyboardHide:(UITapGestureRecognizer*)tap
{
    [self resignRespondersForText];
}


#pragma mark 验证码校验
- (IBAction)verificationNext:(id)sender
{

    [self resignRespondersForText];
   [[UtilToolsClass getUtilTools] addDoLoading];
    [NetRequestClass requestWithUrlForCheckPhoneMessages:self andUrl:[REQUESTHEADER stringByAppendingString:@"userInfo/phoneSmsVerify.asp"] andParam:@{@"loginName":_VVC_phoneNumber,@"zone":_VVC_areaNam,@"verityCode":_VerificationText.text} success:^(NSInteger result) {
          [[UtilToolsClass getUtilTools] removeDoLoading];
        if (result) {
            NSLog(@"// 校验成功");
            [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"Success", @"验证成功")];
            // 验证通过后跳转
            [_timer2 invalidate];
            _againGetSMSBtn.hidden = NO;
            _timeLabel.hidden = YES;

            if ([_VVCsignStr isEqualToString:@"Forget"]) {
                [self performSegueWithIdentifier:@"gotoForget" sender:self];
            }
            else if ([_VVCsignStr isEqualToString:@"Registered"]) {
                [self performSegueWithIdentifier:@"gotoSubmitVC" sender:self];
            }
        }else{
             [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"468description", nil)];
        }
    } failure:^(NSString *error) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        [UtilToolsClass addDisapperAlert:NSLocalizedString(@"", nil) withMessage:error];
    }];

}
// 传值
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{

    if ([_VVCsignStr isEqualToString:@"Forget"]) {
        if ([segue.identifier compare:@"gotoForget"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"FPVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"FPVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"FPVC_phoneNumber"];
            [vc setValue:_VerificationText.text forKey:@"FPVC_SMSCode"];
        }
    }
    else if ([_VVCsignStr isEqualToString:@"Registered"]) {
        if ([segue.identifier compare:@"gotoSubmitVC"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"SVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"SVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"SVC_phoneNumber"];
            [vc setValue:_VerificationText.text forKey:@"SVC_SMSCode"];
        }
    }
}

- (IBAction)againGetSMS:(UIButton*)sender
{
    
    [self loadingUpdateForTimeLable];
    
    [self.view endEditing:YES];
    __weak VerificationVC* verifyVC = self;

    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {

        NSString* str2 = [_VVC_areaNam stringByReplacingOccurrencesOfString:@"+" withString:@""];

        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_VVC_phoneNumber zone:str2 customIdentifier:nil result:^(NSError* error) {
                if (!error) {
                NSLog(@"获取验证码成功");
                [MBProgressHUD showSuccess:NSLocalizedString(@"send", nil)];

                // [self.VVC_window.rootViewController dismissViewControllerAnimated:YES completion:^{

                verifyVC.againGetSMSBtn.hidden = YES;
                verifyVC.timeLabel.hidden = NO;
                verifyVC.timeLabel.text = NSLocalizedString(@"VVCtimelabel", nil);
                [verifyVC.timer2 invalidate];

                timerCount = 0;
                verifyVC.timeLabel.textColor = [UIColor lightGrayColor];
                NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1
                verifyVC.timer2 = timer2;
            }
            else {
                NSString* messageStr = [NSString stringWithFormat:@"%zdescription", error.code];

                [UtilToolsClass addDisapperAlert:NSLocalizedString(@"codesenderrtitle", nil) withMessage:NSLocalizedString(messageStr, nil)];
            }

        }];
    }];
  
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"重新获取验证码", nil) preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

@end
